package biz.yfsoft.app.fastframework.core.document;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import biz.yfsoft.app.fastframework.bo.Bo;
import biz.yfsoft.app.fastframework.kit.FileKit;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class LocalDocument extends Document {

	@Override
	public void save(File file,Bo fRecord) throws DocumentSaveHex {
	}

	@Override
	public void save(String path,Bo fRecord) throws DocumentSaveHex {
		File f = new File(path);
		File desc = new File(fRecord.getStr("path"));
		f.renameTo(desc);
	}

	@Override
	public void save(byte[] data,Bo fRecord) throws DocumentSaveHex {
	}

	@Override
	public void save(InputStream in,Bo fRecord) throws DocumentSaveHex {
		//创建一个file
		File f = new File(fRecord.getStr("path"));
        FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			throw new DocumentSaveHex(e.getMessage());
		}
        byte[] b = new byte[1024];
        int n=0;
        
        try {
			while((n=in.read(b))!=-1){
			   fos.write(b,0,n);
			}
		} catch (IOException e) {
			throw new DocumentSaveHex(e.getMessage());
		}finally{
			try {
				fos.close();
			} catch (IOException e) {
			}
	        try {
				in.close();
			} catch (IOException e) {
			}
		}
	}

	@Override
	public void loadToLocal(String key, String path) throws IOException {
	}

	@Override
	public byte[] loadToMemory(String key) throws IOException {
		return null;
	}

	@Override
	public void init(Object[] args) {
	}

	@Override
	public void loadToLocal(int fileId, String path) throws IOException {
	}

	@Override
	public byte[] loadToMemory(int fileId) throws IOException {
		Record r = Db.findById("sys_file", fileId);
		String path = r.getStr("path");
		return FileKit.toByteArray(path);
	}

	@Override
	public void saveSync(String path, Bo fRecord) throws DocumentSaveHex {
		this.save(path, fRecord);
	}

}
